<template>
	<div class="app-container">
		<yd-form class="yd-form-wraper" :options="formOptions" :model="searchFormData" @form-init="formInited" @search="formInited">
			<template #form-btn>
				<el-button type="primary" @click="searchHandler">查询</el-button>
			</template>
		</yd-form>

		<el-row :gutter="10">
			<el-col :span="11">
				<!--图表-->
				<el-row>
					<el-col :span="12" style="height: 100%" class="box">
						<div class="alarm-pie-title">
							<div class="circle"></div>
							告警类型占比
						</div>
						<div id="alarmTypeProportionChartId" v-loading="loading.alarmTypeProportionChart" style="height: 360px; width: 100%"></div>
					</el-col>

					<el-col :span="12" style="height: 100%" class="box">
						<div class="alarm-pie-title">
							<div class="circle"></div>
							告警等级占比
						</div>
						<div id="alarmLevelPercenChartId" v-loading="loading.alarmLevelProportionChart" style="height: 360px; width: 100%"></div>
					</el-col>
				</el-row>
			</el-col>
			<el-col :span="13">
				<YdTable
					:formData="searchFormData"
					:tableConfig="tableConfig"
					:tableData="tableData.data"
					@sizeChangeHandler="queryAlarmTypeList"
					@currentChangeHandler="queryAlarmTypeList"
					@sortChangeHandler="queryAlarmTypeList"
				></YdTable>
			</el-col>
		</el-row>

		<el-row>
			<el-col :span="24">
				<el-tabs v-model="dataForm.headActiveTabs" size="mini" @tab-click="changeAlarmTypeTab">
					<el-tab-pane
						v-for="(item, index) in dataForm.alarmTypeList"
						:key="index"
						:label="item.alarmTypeName"
						:name="'headerFlag_' + item.alarmTypeId"
						:class="selectTabHandle(dataForm.headActiveTabs)"
					>
						<!-- 列表 -->
						<YdTable
							:formData="searchFormData"
							:tableConfig="alarmTypeTableConfig"
							:tableData="alarmTypeData.data"
							@sizeChangeHandler="getAlarmlListByAramTypeId"
							@currentChangeHandler="getAlarmlListByAramTypeId"
							@sortChangeHandler="getAlarmlListByAramTypeId"
						></YdTable>
					</el-tab-pane>
				</el-tabs>
			</el-col>
		</el-row>
	</div>
</template>

<script setup name="BasicAlarmMerging" lang="tsx">
import {
	getGrid,
	getBusinessAlarmLevelPercent,
	getBusinessAlarmPercent,
	queryBaseIndicatorsList,
	getAramlDetailList,
} from '@/api/bpm/alarm/basic_alarm_merging';
import * as echarts from 'echarts';
import 'echarts-liquidfill';
import { noDataOption } from '@/utils/defaultChartConfig';
import { useRoute, useRouter } from 'vue-router';
import { onActivated, ref, reactive, getCurrentInstance, nextTick } from 'vue';
import { toDecimalFormate } from '@/utils/common';
import { Table } from 'element-plus';
const router = useRouter();
const route = useRoute();
// 选中查询的告警分类
const alarmState = ref(null);
const businessCode = ref(null);
const segmentId = ref(null);
const instance = getCurrentInstance();
const proxy = instance?.proxy;
const searchFormData = reactive<FormModelType>({
	pageSize: 10,
	businessCodes: [],
	alarmStates: [],
	segmentIds: [],
	pageNum: 1,
});
const dataForm = reactive<FormModelType>({
	headActiveTabs: '',
	alarmTypeList: [],
});

// 表单配置
const formOptions = ref<FormOptionType>([
	{
		type: 'select',
		prop: 'systemId',
		label: '系统名称',
		api: {
			name: 'queryAppSystemOptions',
			params: { isStatus: 1 },
		},
		cascaders: [
			{
				cascadersParams: 'businessCodeList',
				api: {
					name: 'queryBusinessOptions',
				},
			},
			{
				cascadersParams: 'segmentIds',
				api: {
					name: 'querySegmentOptions',
				},
			},
		],
	},
	{
		type: 'select',
		prop: 'businessCodeList',
		label: '业务名称',
		attrs: {
			multiple: true,
		},
	},
	{
		type: 'select',
		prop: 'segmentIds',
		label: '网端名称',
		attrs: {
			multiple: true,
		},
	},
	{
		type: 'select',
		prop: 'alarmStates',
		label: '告警分类',
		children: [
			{
				label: '普通告警',
				value: 1,
			},
			{
				label: '失败告警',
				value: 0,
			},
		],
		attrs: {
			multiple: true,
		},
	},
	{
		type: 'select',
		prop: 'dataCenters',
		label: '数据中心',
		isInitValue: false,
		api: {
			name: 'queryDataCenter',
		},
	},
	{
		type: 'date-picker',
		prop: 'dateRange',
		span: 8,
		dateType: 'datetimerange',
		label: '时间范围',
		enableCrossDay: true,
	},
]);

const alarmTypeTableConfig = reactive<TableConfigType>({
	columns: [
		{
			label: '服务响应时长',
			prop: 'alarmResultCode',
			width: 200,
		},
		{
			label: '告警等级',
			prop: 'alarmLevelName',
		},
		{
			label: '告警次数',
			prop: 'alarmCount',
			// renderXss: (row, val) => {
			//   return
			// <
			//   span
			//   style = "color: #ff9a0c" > {val} < /span>;
			// },
			sortable: true,
		},
		{
			label: '系统名称',
			prop: 'systemName',
		},
		{
			label: '网端名称',
			prop: 'segmentName',
		},
		{
			label: '业务名称',
			prop: 'businessName',
		},
		{
			label: '步骤名称',
			prop: 'stepName',
		},
		{
			label: '资源识别串',
			prop: 'identifyCharacter',
			width: 200,
		},
		{
			label: '告警开始时间',
			prop: 'startTime',
			sortable: true,
		},
		{
			label: '告警结束时间',
			prop: 'endTime',
			sortable: true,
		},
	],
	pagination: {
		pageNum: 1,
	},
	loading: true,
	disableOrderNumber: true,
});
// 图表对象
const chart = reactive<anyObj>({
	alarmTypeProportionChart: null,
	alarmLevelPercenChart: null,
});

const alarmTypeData = reactive({ data: [] });

function formatNumber(array: any) {
	if (array instanceof Object) {
		Object.keys(array).forEach((key) => {
			if (array[key] !== '' && array[key] !== undefined) {
				array[key] = Number(array[key]);
			}
		});
	}
}
/**
 * 查询各告警类型对应的告警详情列表
 */
function changeAlarmTypeTab(tab: anyObj) {
	alarmTypeTableConfig.columns[0].label = tab.props.label;
	dataForm.alarmTypeList.forEach((item: anyObj) => {
		if (tab.props.name === 'headerFlag_' + item.alarmTypeId) {
			searchFormData.alarmTypeId = item.alarmTypeId;
			alarmTypeData.data = [];
			// alarmTypeData.total = 0;
			alarmTypeTableConfig.pagination!.total = 0;
			getAlarmlListByAramTypeId();
		}
	});
}
// function handleSelectChange(key) {
// 	searchFormData.businessCodes = [''];
// 	searchFormData.segmentIds = [''];
// }
//tab是否选择样式
function selectTabHandle(selectVal: any) {
	if (selectVal) {
		return 'selectTabClass';
	}
	return 'noSelectTabClass';
}

// 加载层
const loading = reactive({
	alarmTypeProportionChart: false,
	alarmLevelProportionChart: false,
});
// 初始化图表对象
function initChart() {
	chart.alarmTypeProportionChart = echarts.init(document.getElementById('alarmTypeProportionChartId') as HTMLElement);
	chart.alarmLevelPercenChart = echarts.init(document.getElementById('alarmLevelPercenChartId') as HTMLElement);
}

// 查询告警等级占比图表（环形图）
function renderAlarmLevelPercenChart() {
	// searchFormData.systemId = 1
	loading.alarmLevelProportionChart = true;
	//请求数据
	getBusinessAlarmLevelPercent(searchFormData).then((res: ApiResponse) => {
		loading.alarmLevelProportionChart = false;
		chart.alarmLevelPercenChart.clear();
		if (res.code !== 0) {
			proxy?.$message.warning(res.msg);
			if (res.code !== 1003) {
				noDataOption(chart.alarmLevelPercenChart, {
					textStyle: { color: '#fff', formatter: '暂无告警数据~' },
				});
				return;
			}
		}
		if (res.data.length === 0) {
			noDataOption(chart.alarmLevelPercenChart, {
				textStyle: { color: '#fff', formatter: '暂无告警数据~' },
			});
			return;
		}
		//有数据,根据请求结果重新封装数组
		let alarmLevelProportions: any[] = [];
		res.data.forEach((element: anyObj) => {
			if (element.alarmCount > 0) {
				alarmLevelProportions.push({
					// id: element.id,
					name: element.alarmLevelName,
					value: element.alarmCount,
				});
			}
		});
		const chartIns = chart.alarmLevelPercenChart;
		//渲染图表
		renderProportionChart(chartIns, alarmLevelProportions);
	});
}

// 请求告警类型占比数据并渲染
function renderAlarmTypeProportionChart() {
	loading.alarmTypeProportionChart = true;
	//请求数据
	getBusinessAlarmPercent(searchFormData).then((res: ApiResponse) => {
		loading.alarmTypeProportionChart = false;
		chart.alarmTypeProportionChart.clear();
		if (res.code !== 0) {
			proxy?.$message.warning(res.msg);
			if (res.code !== 1003) {
				noDataOption(chart.alarmTypeProportionChart, {
					textStyle: { color: '#fff', formatter: '暂无告警数据~' },
				});
				return;
			}
		}
		if (res.data.length === 0) {
			noDataOption(chart.alarmTypeProportionChart, {
				textStyle: { color: '#fff', formatter: '暂无告警数据~' },
			});
			return;
		}
		//有数据,根据请求结果重新封装数组
		let alarmTypeProportions: any[] = [];
		res.data.forEach((element: anyObj) => {
			if (element.alarmCount > 0) {
				alarmTypeProportions.push({
					id: element.id,
					name: element.alarmTypeName,
					value: element.alarmCount,
				});
			}
		});
		const chartIns = chart.alarmTypeProportionChart;
		//渲染图表
		renderProportionChart(chartIns, alarmTypeProportions);
	});
}

// 公共方法:渲染比例图表
function renderProportionChart(chartIns: anyObj, valueArr: any[]) {
	// 有数据
	chartIns.setOption({
		// 调色盘
		color: ['#fe5578', '#ff7d4f', '#6f81f7', '#1dc69d', '#00ffff', '#e5ba43', '#25b2ff', '#13eecc'],
		// 悬浮提示
		tooltip: {
			trigger: 'item',
			formatter: function (params: anyObj) {
				let label = '';
				if (params.data) {
					label = params.data.name + ': ' + params.data.value;
				}
				return label;
			},
			confine: true,
		},
		series: [
			{
				name: '占比',
				type: 'pie',
				minAngle: 12,
				radius: ['30%', '45%'],
				center: ['50%', '50%'],
				avoidLabelOverlap: true,
				// 标签文本
				label: {
					formatter: function (params: anyObj) {
						let percent = params.percent + '%';
						let paramsName = params.name;
						let newParamsName = '';
						let paramsNameNumber = params.length;
						let provideNumber = 4;
						let rowNumber = Math.ceil(paramsNameNumber / provideNumber);
						if (paramsNameNumber > provideNumber) {
							for (let p = 0; p < rowNumber; p++) {
								let tempStr = '';
								let start = p * provideNumber;
								let end = start + provideNumber;
								if (p === rowNumber - 1) {
									tempStr = params.substring(start, paramsNameNumber);
								} else {
									tempStr = params.substring(start, end) + '\n';
								}
								newParamsName += tempStr;
							}
						} else {
							newParamsName = paramsName;
						}
						return newParamsName + '\n' + percent;
					},
					top: 100,
				},
				// 标签线
				labelLine: {
					length: 20,
					length2: 20,
					lineStyle: {
						type: 'dashed',
					},
				},
				// 高亮状态
				emphasis: {
					label: {
						show: true,
						fontSize: '14',
						fontWeight: 'bold',
					},
				},
				data: valueArr,
			},
		],
	});
}

// 查询告警类型tabs
function handlerAlarmTypeList() {
	let form = {
		...searchFormData,
		pageSize: -1,
		pageNum: 0,
	};
	getGrid(form).then((res: ApiResponse) => {
		if (res.code !== 0) {
			proxy?.$message.warning(res.msg);
			return;
		}

		if (res.data.cycleTableMsg) {
			proxy?.$message.warning(res.data.cycleTableMsg);
		}
		// 重置tab 标签列表
		dataForm.alarmTypeList = [];
		// 更换查询条件时,清空标签数组
		if (res.data.data.length > 0) {
			dataForm.alarmTypeList.push(...res.data.data);
			alarmTypeTableConfig.columns[0].label = dataForm.alarmTypeList[0].alarmTypeName;
			dataForm.headActiveTabs = 'headerFlag_' + dataForm.alarmTypeList[0].alarmTypeId;
			searchFormData.alarmTypeId = dataForm.alarmTypeList[0].alarmTypeId;
			getAlarmlListByAramTypeId();
		}
	});
}

const tableConfig = reactive<TableConfigType>({
	columns: [
		{
			label: '告警类型',
			prop: 'alarmTypeName',
		},
		{
			label: '告警数',
			prop: 'alarmCount',
			sortable: true,
			operation: [
				{
					text: undefined,
					rowKey: 'alarmCount',
					color: '#ff9a0c',

					handler: (scope: any) => {
						const row = scope.row;
						let data = JSON.stringify({
							systemId: row.systemId,
							businessCodes: searchFormData.businessCodes,
							segmentIds: searchFormData.segmentIds,
							alarmIndicatorIds: [row.alarmTypeId],
							startTime: searchFormData.startTime,
							endTime: searchFormData.endTime,
							alarmStates: searchFormData.alarmStates,
							category: row.category,
						});
						router.push({
							path: '/business-monitor/monitor-query/base-alarm-list',
							query: {
								data,
							},
						});
					},
				},
			],
		},
		{
			label: '提示告警',
			prop: 'promptAlarmCount',
			sortable: true,
			operation: [
				{
					text: undefined,
					rowKey: 'promptAlarmCount',
					color: '#ff9a0c',

					handler: (scope: any) => {
						const row = scope.row;

						let data = JSON.stringify({
							systemId: row.systemId,
							businessCodes: searchFormData.businessCodes,
							segmentIds: searchFormData.segmentIds,
							alarmIndicatorIds: [row.alarmTypeId],
							startTime: searchFormData.startTime,
							endTime: searchFormData.endTime,
							alarmStates: searchFormData.alarmStates,
							alarmLevelIds: [1],
							category: row.category,
						});
						router.push({
							path: '/business-monitor/monitor-query/base-alarm-list',
							query: {
								data,
							},
						});
					},
				},
			],
		},
		{
			label: '一般告警',
			prop: 'generalAlarmCount',
			sortable: true,
			operation: [
				{
					text: undefined,
					rowKey: 'generalAlarmCount',
					color: '#ff9a0c',

					handler: (scope: any) => {
						const row = scope.row;

						let data = JSON.stringify({
							systemId: row.systemId,
							businessCodes: searchFormData.businessCodes,
							segmentIds: searchFormData.segmentIds,
							alarmIndicatorIds: [row.alarmTypeId],
							startTime: searchFormData.startTime,
							endTime: searchFormData.endTime,
							alarmStates: searchFormData.alarmStates,
							alarmLevelIds: [2],
							category: row.category,
						});
						router.push({
							path: '/business-monitor/monitor-query/base-alarm-list',
							query: {
								data,
							},
						});
						// isWhite("/business/baseAlarmList", {
						//   systemId: row.systemId,
						//   businessCodes: [this.businessCode],
						//   segmentIds: [this.segmentId],
						//   alarmIndicatorIds: [row.alarmTypeId],
						//   startTime: searchFormData.startTime,
						//   endTime: this.searchFormData.endTime,
						//   alarmStates: [this.alarmState],
						//   alarmLevelIds: ["2"],
						//   category: row.category,
						// });
					},
				},
			],
		},
		{
			label: '紧急告警',
			prop: 'mediumAlarmCount',
			sortable: true,
			operation: [
				{
					text: undefined,
					rowKey: 'mediumAlarmCount',
					color: '#ff9a0c',

					handler: (scope: any) => {
						const row = scope.row;
						// isWhite("/business/baseAlarmList", {
						//   systemId: row.systemId,
						//   businessCodes: [businessCode],
						//   segmentIds: [segmentId],
						//   alarmIndicatorIds: [row.alarmTypeId],
						//   startTime: searchFormData.startTime,
						//   endTime: searchFormData.endTime,
						//   alarmStates: [alarmState],
						//   alarmLevelIds: ["3"],
						//   category: row.category,
						// });
						let data = JSON.stringify({
							systemId: row.systemId,
							businessCodes: searchFormData.businessCodes,
							segmentIds: searchFormData.segmentIds,
							alarmIndicatorIds: [row.alarmTypeId],
							startTime: searchFormData.startTime,
							endTime: searchFormData.endTime,
							alarmStates: searchFormData.alarmStates,
							alarmLevelIds: [3],
							category: row.category,
						});
						router.push({
							path: '/business-monitor/monitor-query/base-alarm-list',
							query: {
								data,
							},
						});
					},
				},
			],
		},
		{
			label: '重大告警',
			prop: 'seriousAlarmCount',
			sortable: true,
			operation: [
				{
					text: undefined,
					rowKey: 'seriousAlarmCount',
					color: '#ff9a0c',

					handler: (scope: any) => {
						const row = scope.row;

						let data = JSON.stringify({
							systemId: row.systemId,
							businessCodes: searchFormData.businessCodes,
							segmentIds: searchFormData.segmentIds,
							alarmIndicatorIds: [row.alarmTypeId],
							startTime: searchFormData.startTime,
							endTime: searchFormData.endTime,
							alarmStates: searchFormData.alarmStates,
							alarmLevelIds: [4],
							category: row.category,
						});
						router.push({
							path: '/business-monitor/monitor-query/base-alarm-list',
							query: {
								data,
							},
						});
					},
				},
			],
		},
		{
			label: '最新告警时间',
			prop: 'latestAlarmTime',
			sortable: true,
			width: 200,
		},
	],
	pagination: {
		pageNum: 1,
	},
	loading: true,
});

const tableData = reactive({
	data: [],
});

function getAlarmlListByAramTypeId() {
	getAramlDetailList(searchFormData).then((res: ApiResponse) => {
		alarmTypeTableConfig.loading = false;
		if (res.code === 0) {
			alarmTypeData.data = res.data.data;
			alarmTypeTableConfig.pagination!.total = res.data.total;
		} else {
			alarmTypeData.data = [];
			alarmTypeTableConfig.pagination!.total = 0;
			proxy?.$message.warning(res.msg);
		}
		// if (res.cycleTableMsg) {
		// 	proxy?.$message.warning(res.cycleTableMsg);
		// }
	});
}

function queryAlarmTypeList() {
	getGrid(searchFormData).then((res: ApiResponse) => {
		tableConfig.loading = false;
		if (res.code === 0) {
			tableData.data = res.data.data;
			tableConfig.pagination!.total = res.data.total;
		} else {
			tableData.data = [];
			tableConfig.pagination!.total = 0;
			proxy?.$message.warning(res.msg);
		}
		// if (res.cycleTableMsg) {
		// 	proxy?.$message.warning(res.cycleTableMsg);
		// }
	});

	// 标签tab 的 label 名字
	handlerAlarmTypeList();
}
function searchHandler() {
	//告警类型占比图
	renderAlarmTypeProportionChart();
	//告警等级占比图
	renderAlarmLevelPercenChart();
	/**
	 * 告警类型统计列表查询
	 */
	queryAlarmTypeList();
}

// 表单初始化成功
const formInited = () => {
	// 初始化图表对象
	initQuery(route.query, searchFormData);
	initChart();
	searchHandler();
};
// 格式化传过来的参数
function initQuery(query: anyObj, formData: FormModelType) {
	try {
		let data = JSON.parse(query.data);
		for (let key in data) {
			formData[key] = data[key];
		}
	} catch {
		for (let key in query) {
			formData[key] = query[key];
		}
	}
	if (formData.systemId) {
		formData.systemId += '';
	}
	if (formData.segmentIds) {
		formData.segmentIds = formData.segmentIds.map((item: any) => String(item));
	}
}
initQuery(route.query, searchFormData);
</script>

<style scoped lang="scss">
@mixin title-box {
	display: flex;
	align-items: center;
}
.chart-container {
	background-color: rgba(29, 39, 75, 0.31);
	border: unset;
	border-radius: 12px;
	position: relative;
}
.bg-chart {
	/* background: #1c2b5d;*/
	border-radius: 15px;
	margin: 20px;
}
.system-health-textBox {
	display: flex;
	align-items: center;
	height: 84%;
	.vertical-center {
		width: 100%;
	}
	.system-health-item {
		color: #2beded;
		font-size: 14px;
		margin-bottom: 8px;
	}
	.text-white {
		color: #ffffff;
	}
	.text-red {
		color: #fe5578;
	}
	.text-yellow {
		color: #ff7d4f;
	}
	.text-blue {
		color: #2beded;
	}
}
.title-icon {
	content: '';
	background: #2beded;
	width: 10px;
	height: 9px;
	border-radius: 50%;
	margin-right: 2px;
	vertical-align: 110%;
	position: relative;
	display: block;
	left: 15px;
	top: 20px;
}
.circle {
	display: inline-block;
	width: 8px;
	height: 8px;
	margin-left: 8px;
	margin-right: 8px;
	background-color: #2beded;
	border-radius: 50%;
	-moz-border-radius: 50%;
	-webkit-border-radius: 50%;
}
.alarm-pie-title {
	height: 13%;
	display: flex;
	align-items: center;
	justify-content: center;
	color: #ffffff;
	font-size: 18px;
	font-weight: bold;
}
.title-label {
	color: #ffffff;
	font-size: 18px;
	font-weight: bold;
	margin-right: 5px;
}
.system-health-title {
	height: 16%;
	position: absolute;
	top: 5px;
	left: 5px;
	@include title-box;
}

.card {
	background-color: rgba(29, 39, 75, 0.31);
	border: unset;
	border-radius: 12px;
	padding: 10px;
}
.icon-cls {
	width: 20px;
	height: 20px;
	color: #00ffff;
}

.box {
	background: #386d96;
}
:deep(.el-tabs) {
	.el-tabs__item {
		color: #fff;
	}
	.el-tabs__item.is-active,
	.el-tabs__item:hover {
		color: let(--el-color-primary);
	}
}
</style>
